<template>
  <view class="upload-image-container">
    <!-- 显示已上传的图片列表 -->
    <view class="image-list">
      <!-- 已上传的图片 -->
      <view v-for="(item, index) in uploadedImages" :key="index" class="image-item">
        <image
          :src=" this.$baseUrl + item.url"
          class="image-preview"
          @click="handleModifyImage(index)"
        />
        <!-- 删除按钮 -->
        <view class="delete-btn" @click="handleDeleteImage(index)">
          <text class="delete-text">X</text>
        </view>
      </view>

      <!-- 占位样式 -->
		<view class="placeholder" v-if="uploadedImages.length < limit" @click="chooseImage">
		  <uni-icons class="placeholder-text" type="camera" size="35" color="#666" />
		  <text class="count">{{ uploadedImages.length }}/{{ limit }}</text> <!-- 显示当前上传数量和限制 -->
		</view>
	</view>
</view>
</template>

<script>
export default {
  props: {
	limit: {
	  type: Number,
	  default: 4
	},
    uploadUrl: {
      type: String,
      required: true, // 必须传入后端接口地址
    },
    buttonText: {
      type: String,
      default: '选择图片', // 默认显示的文字
    },
    uploadedImages: {  // 存储已成功上传的图片 URL
      type: Array,
      required: true,
    }
  },
  data() {
    return {
      modifyIndex: -1, // 用于记录当前正在修改的图片索引
    };
  },
  methods: {
    // 选择图片并自动上传
    chooseImage() {
      uni.chooseImage({
        count: 1, // 每次只能选择一张图片
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0]; // 获取选择的图片路径
          this.uploadImage(filePath); // 自动上传
        },
        fail: (err) => {
          console.error('选择图片失败：', err);
        },
      });
    },
    // 上传图片
    uploadImage(filePath) {
      uni.uploadFile({
        url: this.uploadUrl, // 上传接口地址
        filePath: filePath,
        name: 'file',
        success: (uploadFileRes) => {
          const response = uploadFileRes.data; // 假设服务器返回 图片路径
          if (response) {
            const newImage = { url: "/api/file/download" + response };
            if (this.modifyIndex !== -1) {
              // 如果正在修改图片，则替换对应的图片
              this.uploadedImages[this.modifyIndex] = newImage;
              this.modifyIndex = -1; // 重置修改状态
            } else {
              // 如果是新上传的图片，直接添加到已上传列表
              this.uploadedImages.push(newImage);
            }
            this.$emit('upload-success', this.uploadedImages); // 通知父组件上传成功
          } else {
            uni.showToast({ title: '上传失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('上传失败：', err);
          this.$emit('upload-fail', err); // 通知父组件上传失败
        },
      });
    },
    // 点击已上传的图片进行修改
    handleModifyImage(index) {
      this.modifyIndex = index; // 记录正在修改的图片索引
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0];
          this.uploadImage(filePath); // 上传新图片，替换原有图片
        },
        fail: (err) => {
          console.error('修改图片失败：', err);
        },
      });
    },
    // 删除图片
    handleDeleteImage(index) {
      this.uploadedImages.splice(index, 1); // 删除指定索引的图片
      this.$emit('delete-success', this.uploadedImages); // 通知父组件删除成功
    },
  },
};
</script>

<style scoped>
.upload-image-container {
  display: flex;
  flex-direction: column;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: flex-start; /* 左对齐 */
}

.image-item {
  position: relative;
  width: 75px; /* 每张图片占用的空间 */
  height: 75px;
  overflow: hidden;
  border-radius: 8px;
  background-color: #f5f5f5; /* 统一的背景色 */
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #ddd; /* 边框样式 */
}

.placeholder {
  width: 75px; /* 每张图片占用的空间 */
  height: 75px;
  display: flex;
  flex-direction: column; /* 使图标和文本垂直排列 */
  align-items: center;
  justify-content: center;
  border: 2px dashed #ccc;
  border-radius: 8px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.placeholder:hover {
  background-color: #e1e1e1; /* 悬浮时改变背景色 */
}

.placeholder-text {
  color: #aaa;
}

.count {
  font-size: 12px;
  color: #666;
  margin-top: 4px; /* 给文本添加一些间距 */
}


.delete-btn {
  position: absolute;
  top: -5px; /* 删除按钮离图片的顶部稍微偏移 */
  right: -5px; /* 删除按钮离图片的右边稍微偏移 */
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  padding: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.delete-btn:hover {
  background-color: rgba(0, 0, 0, 0.8); /* 悬浮时改变背景色 */
}

.delete-text {
  color: white;
  font-size: 16px;
}

.delete-btn:active {
  transform: scale(0.9); /* 点击删除按钮时缩小 */
}

</style>
